<template>
  <el-row>
    <el-col :span="24">
      <ContentWrap>
        <!-- 搜索栏 -->
        <el-form
          ref="queryFormRef"
          :inline="true"
          :model="queryParams"
          class="-mb-15px"
          label-width="90px"
        >
          <el-form-item
            v-for="item in navigationals"
            :key="item"
            :label="item.fieldDesc"
            :prop="item.name"
          >
            <el-cascader
              v-if="item.name === 'classify'"
              class="!w-240px"
              :options="item.tree"
              :props="defaultProps"
              @change="(checked) => handleBaseValue(checked, item.name)"
            />
            <el-input
              v-show="item.name === 'title'"
              class="!w-240px"
              v-model="queryParams.title"
              clearable
              placeholder="请输入名称"
              @keyup.enter="handleQuery"
            />
            <el-input
              v-show="item.name === 'author'"
              class="!w-240px"
              v-model="queryParams.author"
              clearable
              placeholder="请输入作者"
              @keyup.enter="handleQuery"
            />
            <el-input
              v-show="item.name === 'publishername'"
              class="!w-240px"
              v-model="queryParams.publishername"
              clearable
              placeholder="请输入出版社"
              @keyup.enter="handleQuery"
            />
            <el-input
              v-show="item.name === 'name'"
              class="!w-240px"
              v-model="queryParams.name"
              clearable
              placeholder="请输入名称"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-240px"
              end-placeholder="结束日期"
              start-placeholder="开始日期"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
            <!--            <el-button v-hasPermi="[-->
            <!--              'resource:meta:add',-->
            <!--              'resource:sps:add',-->
            <!--              'resource:standard:add'-->
            <!--              ]" plain type="primary" @click="add">-->
            <!--              <Icon class="mr-5px" icon="ep:plus" />-->
            <!--              添加-->
            <!--            </el-button>-->
            <el-button
              plain
              v-hasPermi="['resource:meta:release']"
              type="success"
              @click="batchRelease"
            >
              <Icon class="mr-5px" icon="material-symbols:download" />
              审核
            </el-button>
            <el-button
              plain
              v-hasPermi="['resource:meta:release']"
              type="success"
              @click="batchIssue"
            >
              <Icon class="mr-5px" icon="material-symbols:download" />
              发布
            </el-button>
            <el-button plain type="danger" @click="handleDelete()" icon="delete"
              >批量删除</el-button
            >
            <el-button plain type="danger" @click="recycle(id)" icon="delete"> 回收站 </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list.list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" prop="create_time" label="创建日期" sortable />
          <el-table-column
            v-for="(column, index) in list.columns"
            :key="index"
            :prop="column.prop"
            :label="column.label"
            align="center"
            :width="column.prop === 'id' ? 55 : ''"
          >
            <template #default="scope">
              <el-image
                v-if="imaged(scope.row[column.prop])"
                :src="buildImage(column.prop, scope.row)"
                style="max-width: 50px"
              >
                <template #error>
                  <el-image :src="bookLogo" style="max-width: 50px"></el-image>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status" label="资源状态">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.RESOURCE_STATUS" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="230px">
            <template #default="scope">
              <el-button link type="primary" @click="impResource(id, scope.row.id)">
                资源列表
              </el-button>
              <el-button link type="primary" @click="metaVersion(id, scope.row.id)">
                版本管理
              </el-button>
              <el-button
                link
                type="primary"
                v-hasPermi="[
                  'resource:meta:update',
                  'resource:sps:update',
                  'resource:standard:update'
                ]"
                @click="updateResource(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button link type="primary" @click="checkOverlap(scope.row)">查重</el-button>
              <el-button link type="primary" v-if="meta.detailRoute" @click="detail(scope.row.id)">
                详情
              </el-button>
              <el-button link type="danger" @click="deleted(scope.row.id)"> 删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <Pagination
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNo"
          :total="total"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>
  <el-dialog
    v-model="showSelectHouseDialogFlag"
    title="选择资源外壳"
    center
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="40%"
    @close="closeSelectHouseDialog"
  >
    <el-select v-model="house" placeholder="请选择资源外壳" style="width: 100%">
      <el-option v-for="item in houses" :key="item" :label="item.name" :value="item.id" />
    </el-select>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addResource">下一步</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="showFormDialogFlag"
    :title="formTitle"
    left
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="85%"
    @close="closeForm"
    destroy-on-close
  >
    <v-form-render
      ref="vFormRef"
      :form-json="formJson"
      :form-data="formData"
      :option-data="optionData"
    />
    <template #footer>
      <div class="dialog-footer">
        <span v-if="prompt" style="display: block; margin-bottom: 10px; color: red">{{
          prompt
        }}</span>
        <el-button type="primary" @click="saveResource">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 导入加进度条 -->
  <el-dialog v-model="uplod" title="导入" width="800">
    <!-- :headers="{'Content-Type':localStorage.getItem('ACCESS_TOKEN')}" 这是上传必带的token不然你根本上传不了 这块是默认行为-->
    <el-upload
      v-model:file-list="fileList"
      :before-upload="beforeUpload"
      :on-success="onsuccess"
      class="upload-demo"
      drag
      :action="UPLOAD_URL"
      :headers="HEADERS"
      multiple
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text"> 点击或者 <em>拖拽</em> </div>
      <template #tip>
        <div class="el-upload__tip"> 只支持上传zip文件 </div>
      </template>
    </el-upload>
  </el-dialog>

  <Application
    :metaId="id"
    type="10"
    :columns="list.columns"
    :list="selectedItems"
    ref="downAppRef"
  />

  <AuditForm ref="auditRef" @success="getList"></AuditForm>
  <OverlapListForm ref="overlapListRef" @success="getList"></OverlapListForm>
  <el-dialog v-model="dialogState" title="提示" width="500">
    <h3>需要添加资源外壳，是否跳转到资源外壳页面</h3>
    <template #footer>
      <div class="">
        <el-button @click="dialogState = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { h, reactive, ref, watch } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import * as classifyApi from '@/api/classify'
import { useRoute } from 'vue-router'
import * as metaApi from '@/api/meta'
import * as houseApi from '@/api/house/book'
import router from '@/router'
import Application from '@/views/download/application.vue'
import download from '@/utils/download'
import { DICT_TYPE } from '@/utils/dict'
import bookLogo from '@/assets/imgs/bookLogo.webp'
import { UploadFilled } from '@element-plus/icons-vue'
import { getAccessToken } from '@/utils/auth'
import AuditForm from '@/views/resource/meta/AuditForm.vue'
import OverlapListForm from '@/views/resource/meta/OverlapListForm.vue'

const UPLOAD_URL = import.meta.env.VITE_BASE_URL + '/admin-api/uploadOld'
const HEADERS = { Authorization: 'Bearer ' + getAccessToken() }
const route = useRoute()
const fileList = ref([])
const dialogState = ref(false)
const uplod = ref(false)
// 上传文件的函数，使用 axios 发送 POST 请求
const onsuccess = (res) => {
  console.log(res)
  if (!res.code) {
    console.log('上传成功', fileList.value)
  } else {
    ElMessage({
      message: '上传失败',
      type: 'error' // 消息类型，可以根据需要指定
    })
    fileList.value.pop()
  }
}
const validateFiles = (files: File[]) => {
  // 调用接口进行文件验证操作
  // 示例：axios.post('your-validation-api-endpoint', formData)
  const formData = new FormData()
  files.forEach((file) => {
    formData.append('files', file)
  })

  // 发送上传文件的请求
  fetch(UPLOAD_URL, {
    method: 'POST',
    headers: HEADERS,
    body: formData
  })
    .then((response) => {
      console.log(response, 'response')
    })
    .catch((error) => {
      // 处理请求错误的逻辑
      console.error('请求错误重新发送', error)
    })
}
const beforeUpload = async (file) => {
  const isZip = file.name.toLowerCase().endsWith('.zip')
  if (!isZip) {
    // 使用 Element Plus 的消息提示
    ElMessage({
      message: '只能上传 .zip结尾的文件',
      type: 'error' // 消息类型，可以根据需要指定
    })
  }
  return isZip
}
const uri = window.location.href.split('/')
const id = Number(uri[uri.length - 1])
const downAppRef = ref<any>()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  status: 1,
  statusArr: [1, 2, 3], //多状态标识
  keyword: null,
  author: null,
  press: null,
  createTime: []
})

const showFormDialogFlag = ref(false)

const formTitle = ref('添加')

const loading = ref(false)

const list = ref([])

const total = ref(0)

const formJson = ref({
  widgetList: [],
  formConfig: {}
})

const formData = ref({})

const optionData = ref({})

interface Tree {
  [key: string]: any
}
const handleConfirm = () => {
  dialogState.value = false
  router.push('/housing/index')
}

const filterText = ref('')
const treeRef = ref<InstanceType<typeof ElTree>>()
const house = ref(null)
const houses = ref([])
const handleQuery = () => {
  getList()
}

const defaultProps = {
  label: 'name',
  value: 'id'
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})

const detail = (dataId) => {
  // router.push(meta.value.detailRoute + '?metaId=' + id + '&id=' + dataId)
  // router.push({ path: meta.value.detailRoute, query: { metaId: id, id: dataId } })
  router.push({
    path: meta.value.detailRoute,
    query: { metaId: id, detailsId: dataId, buttonState: true }
  })
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

const data = ref<Tree>([])

const queryClassify = async () => {
  if (navigationals.value.length > 0) {
    for (const item of navigationals.value) {
      if (item.name === 'classify') {
        data.value = await classifyApi.classifyTree(item.classifyCode)
        item.tree = data.value
      }
      if (item.name === 'title') queryParams[item.name]
      if (item.name === 'author') queryParams[item.name]
      if (item.name === 'publishername') queryParams[item.name]
      if (item.name === 'name') queryParams[item.name]
    }
  }
}

const getList = async () => {
  list.value = await metaApi.selectData(id, queryParams).then((res) => {
    res.columns.forEach((item, index) => {
      if (res.columns[index].prop === 'create_time') res.columns.splice(index, 1)
      if (res.columns[index].prop === 'delete_time') res.columns.splice(index, 1)
    })
    return res
  })
  total.value = list.value.total
}
const meta = ref({})
const fieldList = ref([])
const navigationals = ref([])
const leftSpan = ref(0)
const rightSpan = ref(24)
const selectForm = async () => {
  let res = await metaApi.selectForm(id)
  meta.value = res
  let f = JSON.parse(res.tableForm)
  console.log(f)
  formJson.value.widgetList = f.widgetList
  formJson.value.formConfig = f.formConfig
  console.log(res)
  res.fieldList.forEach((item) => {
    if (item.navigational) {
      rightSpan.value = 18
      leftSpan.value = 6
      navigationals.value.push(item)
    }
    fieldList.value.push({
      key: item.id,
      label: item.fieldDesc
    })
  })
  queryClassify()
}

const showSelectHouseDialogFlag = ref(false)
const prompt = ref<string>()
const addResource = async () => {
  console.log(house.value)
  if (!house.value && meta.value.shelled) {
    ElMessage('请选择资源外壳!')
    return
  }
  if (house.value && meta.value.shelled) {
    let result = await houseApi.selectInfo(house.value, id)
    if (result && result.length > 0) {
      prompt.value = '注：'
      result.forEach((res) => {
        prompt.value = prompt.value + res.fieldDesc + ','
      })
      prompt.value = prompt.value?.substring(0, prompt.value?.length - 1)
      prompt.value = prompt.value + '需在入库审核前填充。'
    }
    console.log(result)
  }
  updated = false
  showSelectHouseDialogFlag.value = false
  showFormDialogFlag.value = true
}
const closeSelectHouseDialog = () => {
  showSelectHouseDialogFlag.value = false
}

function isValidJson(str) {
  if (str.startsWith('{') || str.startsWith('[')) {
    if (str.endsWith(']') || str.endsWith('}')) {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
  try {
    JSON.parse(str)
    return true
  } catch (e) {
    return false
  }
}

function isNumber(str: string): boolean {
  return /^\d+$/.test(str) // 只包含数字的正则表达式
}

const imaged = (row) => {
  if (!row) {
    return false
  }
  if (isNumber(row)) {
    return false
  }
  return isValidJson(row)
}
const buildImage = (name, row) => {
  if (JSON.parse(row[name]).length > 0) {
    // if (row[name]) {
    return JSON.parse(row[name].replaceAll('\\', ''))[0].url
    // return JSON.parse(row[name])[0].url
  } else {
    return ''
  }
}
const vFormRef = ref<any>()
let updated = false
const saveResource = async () => {
  let formDataJson = await vFormRef.value.getFormData()
  formDataJson.house_id = house.value
  console.log(house.value)
  console.log(formDataJson)
  //formDataJson.cover = JSON.stringify(formDataJson.cover)
  if (updated && updateId.value > 0) {
    await metaApi.updateMetaData(id, updateId.value, formDataJson)
  } else {
    await metaApi.createData(id, formDataJson)
  }
  showFormDialogFlag.value = false
  getList()
}
const updateId = ref(0)
const updateResource = async (rid) => {
  updated = true
  formTitle.value = '修改'
  updateId.value = rid
  showFormDialogFlag.value = true
  let res = await metaApi.selectMetaDataOne(id, rid)
  //vFormRef.value.setFieldValue('id', rid)
  await vFormRef.value.setFormData(res)
}

//版本管理
const metaVersion = async (metaId, id) => {
  router.push({
    path: '/resource/meta/version',
    query: { metaId: metaId, metaName: meta.value.metaName, id: id }
  })
}
//进入资源列表
const impResource = (metaId, id) => {
  console.log(metaId)
  // router.push('/resource/meta/file?metaId=' + metaId + '&id=' + id)
  router.push({ path: '/resource/meta/file', query: { metaId: metaId, id: id } })
}
const closeForm = () => {
  //清空表单
  vFormRef.value.resetForm()
  showFormDialogFlag.value = false
}
const showTree = reactive({})
const openTree = (name) => {
  if (showTree[name]) {
    showTree[name] = true
  }
  showTree[name] = !showTree[name]
  console.log(showTree)
}
const selectedItems = ref([])
const handleSelectionChange = (row) => {
  selectedItems.value = row
}
const queryFormRef = ref<any>()
const resetQuery = () => {
  queryFormRef.value.resetFields()
  console.log(queryParams)
  handleQuery()
}
const handleBaseValue = (val, name) => {
  let v = JSON.stringify(val).replace('[', '').replace(']', ',')
  queryParams[name] = v
}
const down = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要下载的数据，不能同时超过10条!')
    return
  }
  let ids = []
  selectedItems.value.forEach((res) => {
    ids.push(res.id)
  })
  const res = await metaApi.download(id, ids.join(';'))
  download.zip(res, new Date().getTime() + '.zip')
}
const message = useMessage()
const deleted = async (rid) => {
  try {
    await message.confirm('确定删除资源吗？')
    let ids = []
    ids.push(rid)
    await metaApi.deleted(id, ids)
    await getList()
  } catch {}
}

const checkParmas = ref({
  metaId: undefined,
  title: undefined
})

const overlapListRef = ref()

/** 查 重 */
const checkOverlap = async (row) => {
  console.log(row)
  checkParmas.value.metaId = id
  checkParmas.value.title = row.fn_title
  await metaApi.checkOverlap(id, checkParmas.value).then((res) => {
    if (res.length > 1) {
      ElMessage.warning('该资源标题已存在重复记录，请选择退回原因!')
      overlapListRef.value.open(res, row.id)
    } else {
      ElMessage.success('该资源未发现重复项，可通过审核!')
    }
  })
}

const auditRef = ref()

const batchRelease = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要审核的数据!')
    return
  }
  if (selectedItems.value.length > 1) {
    ElMessage.warning('只能审核单条数据!')
    return
  }
  let ids = []
  selectedItems.value.forEach((res) => {
    if (res.status == 2) {
      ids.push(res.id)
      auditRef.value.open(10, id, ids, res.fn_title)
    } else {
      ElMessage.warning('请选择审核中的数据审核!')
    }
  })
  // if (ids.length > 0) {
  //   await metaApi.release(id, ids)
  // }
  // await getList()
}

const batchIssue = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要发布的数据!')
    return
  }
  let ids = []
  selectedItems.value.forEach((res) => {
    if (res.status == 1 || res.status == 3) {
      ids.push(res.id)
    } else {
      ElMessage.warning('请选择审核通过的数据发布!')
    }
  })
  if (ids.length > 0) {
    await metaApi.issue(id, ids)
    ElMessage.success('资源发布成功!')
  }
  await getList()
}

const batchAuditing = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要审核的数据!')
    return
  }
  let ids = []
  selectedItems.value.forEach((res) => {
    if (res.status == 0) {
      ids.push(res.id)
    } else {
      return ElMessage.warning('请选择待审的数据审核!')
    }
  })
  if (ids.length > 0) {
    await metaApi.auditing(id, ids)
  }
  await getList()
}

const batchUnRelease = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要取消发布的数据!')
    return
  }
  let ids = []
  selectedItems.value.forEach((res) => {
    if (res.status == 10) {
      ids.push(res.id)
    } else {
      return ElMessage.warning('请选择已发布的数据取消发布!')
    }
  })
  if (ids.length > 0) {
    await metaApi.unRelease(id, ids)
  }
  await getList()
}
// 批量删除
const handleDelete = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要删除的数据!')
    return
  }
  try {
    await message.confirm('确定删除资源吗？')
    let ids = []
    selectedItems.value.forEach((res) => ids.push(res.id))
    await metaApi.deleted(id, ids)
    await getList()
  } catch {}
}
//资源回收站
const recycle = () => {
  router.push({
    path: '/resource/recycle/index',
    query: { id: id }
  })
}
onMounted(() => {
  getList()
  selectForm()
})
</script>
<style scoped lang="scss">
.element-plus-tree {
  display: inline-block !important;
  min-width: 100%;
}

.flex {
  display: flex;
}

.container {
  height: 100%;
  justify-content: space-between;

  .selectTree {
    width: 256px;
    margin-right: 20px;
    background-color: #e9effd;

    .tree-title {
      height: 35px;
      padding: 0 10px;
      margin: 10px 0;
      background-color: #fff;
      border-radius: 5px;
      box-sizing: border-box;
      align-items: center;
      justify-content: space-between;

      b {
        display: block;
        width: 3px;
        height: 45%;
        background-color: #3a8fec;
        border-radius: 2px;
      }

      span {
        flex: 1;
        margin-left: 15px;
        font-size: 15px;
      }
    }
  }

  .content {
    flex: 1;
    overflow: auto;
  }
}

:deep(.el-tree) {
  background-color: transparent;
}

.dialog-footer {
  text-align: center;
}

.el-image {
  margin: 0 auto;
  padding: 1px 1px 1px 1px;
  background: #d4d4d4;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
